package com.jinly.ryder.log.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinly.ryder.common.error.SystemErrorType;
import com.jinly.ryder.log.client.dto.LogsetDTO;
import com.jinly.ryder.log.client.dto.MachineGroupDTO;
import com.jinly.ryder.log.client.dto.TopicInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class Cls2017Client {

    private static final String HOST = "ap-shanghai.cls.tencentcs.com";
    private final String secretId;
    private final String secretKey;
    private RestTemplate restTemplate;

    public Cls2017Client(String secretId, String secretKey) {
        this.secretId = secretId;
        this.secretKey = secretKey;
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5 * 1000);
        factory.setReadTimeout(5 * 1000);
        restTemplate = new RestTemplate(factory);
    }

    public List<LogsetDTO> queryLogsetList() {
        String path = "/logsets";
        Map<String, String> paramMap = new HashMap();
        String result = doRequest(path, HttpMethod.GET, paramMap, null);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject.getJSONArray("logsets").toJavaList(LogsetDTO.class);
    }

    public LogsetDTO createLogset(LogsetDTO logsetDTO) {
        String path = "/logset";
        return doPost(path, logsetDTO, LogsetDTO.class);
    }

    public List<TopicInfoDTO> queryTopicsList(String logsetId) {
        String path = "/topics";
        Map<String, String> paramMap = new HashMap();
        paramMap.put("logset_id", logsetId);
        String result = doRequest(path, HttpMethod.GET, paramMap, null);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject.getJSONArray("topics").toJavaList(TopicInfoDTO.class);
    }

    public TopicInfoDTO createTopic(TopicInfoDTO topicInfo) {
        String path = "/topic";
        return doPost(path, topicInfo, TopicInfoDTO.class);
    }

    public void topicMachineGroup(TopicInfoDTO topicInfo) {
        String path = "/topic/machinegroup";
        Map<String, String> paramMap = new HashMap();
        paramMap.put("topic_id", topicInfo.getTopicId());
        doRequest(path, HttpMethod.PUT, paramMap, topicInfo);
    }

    public List<MachineGroupDTO> queryMachineGroupList() {
        String path = "/machinegroups";
        Map<String, String> paramMap = new HashMap();
        String result = doRequest(path, HttpMethod.GET, paramMap, null);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject.getJSONArray("machine_groups").toJavaList(MachineGroupDTO.class);
    }

    public MachineGroupDTO createMachineGroup(MachineGroupDTO machineGroup) {
        String path = "/machinegroup";
        return doPost(path, machineGroup, MachineGroupDTO.class);
    }

    public MachineGroupDTO updateMachineGroup(MachineGroupDTO machineGroup) {
        String path = "/machinegroup";
        return doPut(path, machineGroup, MachineGroupDTO.class);
    }


    private <T> T doPost(String path, Object body, Class<T> clazz) {
        String result = doRequest(path, HttpMethod.POST, new HashMap<>(), body);
        return JSON.parseObject(result, clazz);
    }

    private <T> T doPut(String path, Object body, Class<T> clazz) {
        String result = doRequest(path, HttpMethod.PUT, new HashMap<>(), body);
        return JSON.parseObject(result, clazz);
    }

    private String doRequest(String path, HttpMethod method, Map<String, String> queryParamMap, Object body) {
        Map<String, String> headerMap = new HashMap();
        headerMap.put("Host", HOST);
        headerMap.put("User-Agent", "AuthSDK");
        String json = null;
        if (body != null) {
            json = JSON.toJSONString(body);
            headerMap.put("Content-Type", "application/json");
            headerMap.put("Content-MD5", DigestUtils.md5DigestAsHex(json.getBytes()));
        }
        try {
            String sign = QcloudClsSignature.buildSignature(secretId, secretKey, method.name(), path, queryParamMap, headerMap, 10000);
            HttpHeaders headers = new HttpHeaders();
            headerMap.forEach((k, v) -> headers.set(k, v));
            headers.set("Authorization", sign);
            HttpEntity httpEntity = new HttpEntity(json, headers);
            String query = queryParamMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
            String url = "https://" + HOST + path + "?" + query;
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, httpEntity, String.class);
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                log.info("ok:{}", responseEntity.getBody());
                return responseEntity.getBody();
            } else {
                log.error("请求{}失败:{}", path, responseEntity.getBody());
                throw SystemErrorType.INTERNAL_SERVER_ERROR.buildError();
            }
        } catch (Exception e) {
            log.error("请求{}失败", path, e);
            throw SystemErrorType.INTERNAL_SERVER_ERROR.buildError();
        }
    }


}
